# 西游记：https://dushu.baidu.com/pc/detail?gid=4306063500
import json

# 所有章节：https://dushu.baidu.com/api/pc/getDetail?data={"book_id":"4306063500"}
# 章节具体内容：https://dushu.baidu.com/api/pc/getChapterContent?data={"book_id":"4306063500","cid":"4306063500|1569782244","need_bookinfo":1}


import requests
import asyncio
import aiohttp
import aiofiles
import time

'''
1. 同步操作：访问 getCatalog 拿到所有章节的cid 和名称
2. 异步操作：访问 getChapterContent 下载所有的文章内容
'''


async def aiodownload(cid, b_id, title):
    data = {
        "book_id": b_id,
        "cid": f"{b_id}|{cid}",
        "need_bookinfo": 1
    }
    data = json.dumps(data)
    url = f'https://dushu.baidu.com/api/pc/getChapterContent?data={data}'

    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:  # async with 异步请求不需要关闭连接
            # 请求回来了，写入文件
            dic = await resp.json()
            async with aiofiles.open("../爬虫文件/西游记/" + title + '.txt', mode='w', encoding='utf-8') as file:
                await file.write(dic['data']['novel']['content'])  # await： 读取内容是异步的，需要 await 挂起操作


async def getCatalog(url):
    resp = requests.get(url)
    resp.close()
    # print(resp.json())
    dic = resp.json()
    tasks = []
    for item in dic['data']['novel']['items']:
        cid = item['cid']
        title = item['title']
        # 准备异步任务
        tasks.append(asyncio.create_task(aiodownload(cid, b_id, title)))

    await asyncio.wait(tasks)


if __name__ == '__main__':
    b_id = "4306063500"
    url = 'https://dushu.baidu.com/api/pc/getCatalog?data={"book_id":"' + b_id + '"}'
    # 一次性启动多个任务（协程）
    t1 = time.time()
    asyncio.run(getCatalog(url))
    print('共耗时：', time.time() - t1)
